<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="本文主要对 cookie、localStorage、sessionStorage、indexDB等知识点进行总结。">
<meta property="og:type" content="article">
<meta property="og:title" content="js中的数据存储">
<meta property="og:url" content="https://huangrenhao.gitee.io/2019/11/10/js-cookie-storage/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="本文主要对 cookie、localStorage、sessionStorage、indexDB等知识点进行总结。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-11-18T10:57:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js中的数据存储">
<meta name="twitter:description" content="本文主要对 cookie、localStorage、sessionStorage、indexDB等知识点进行总结。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2019/11/10/js-cookie-storage/">





  <title>js中的数据存储 | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2019/11/10/js-cookie-storage/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js中的数据存储</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-10T08:39:04+08:00">
                2019-11-10
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/11/10/js-cookie-storage/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/11/10/js-cookie-storage/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文主要对 cookie、localStorage、sessionStorage、indexDB等知识点进行总结。<a id="more"></a></p>
<h3 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h3><h4 id="限制："><a href="#限制：" class="headerlink" title="限制："></a>限制：</h4><ul>
<li>绑定在特定的域名下，当设定一个 cookie 后，再给创建它的域名发送请求都会包含这个 cookie 。确保存储在 cookie 中的信息只能让批准的接受者访问，无法被其他域访问。</li>
<li>每个域的 cookie 总数是有限的，不同浏览器之间各不相同。超过单个域名限制后再设 cookie 浏览器会清除以前设置的 cookie 。一个域下所有 cookie 的尺寸也有限制，大多数浏览器都有大约 4096B （加减1）的长度限制。如果尝试创建超过最大尺寸限制的 cookie 则该 cookie 会被丢掉。</li>
</ul>
<h4 id="构成："><a href="#构成：" class="headerlink" title="构成："></a>构成：</h4><ul>
<li>名称：唯一确定 cookie 的名称，不区分大小写。cookie 的名称必须经过 URL 编码。</li>
<li>值：存储在 cookie 中的字符串值。值必须经过 URL 编码。</li>
<li>域：cookie 对于哪个域是有效的。</li>
<li>路径：对于指定域中的那个路径应该向服务器发送 cookie </li>
<li>失效时间：表示 cookie 何时应该被删除的时间戳即何时应该停止向服务器发送这个 cookie。<strong>默认情况下会话结束时即将所有的 cookie 删除。</strong></li>
<li>安全标志：指定后 cookie 只有在使用 SSL 连接的时候才发送到服务器。</li>
</ul>
<p>构成中的域、路径、失效时间、安全标志都是服务器给浏览器的指示（在 Set-Cookie 首部中以分号加空格分隔），并不会作为发送到服务器的 cookie 信息的一部分（只有名值对才会被发送）</p>
<h4 id="javascript操作cookie"><a href="#javascript操作cookie" class="headerlink" title="javascript操作cookie"></a>javascript操作cookie</h4><p><code>document.cookie</code>可以用来获取 cookie ，返回当前页面可用的所有 cookie 名值对字符串（分号加空格间隔）。y也可以用于设置 cookie ，直接赋值操作并不会覆盖 cookie ，一般会被添加到现有的 cookie 集合中，除非设置的 cookie 名称已经存在。</p>
<h4 id="子cookie"><a href="#子cookie" class="headerlink" title="子cookie"></a>子cookie</h4><p>绕开浏览器的单域名下 cookie 数限制。子cookie 是存放在单个 cookie 中的更小段的数据。最常见格式如下：<code>name=name1=value1&amp;name2=value2&amp;name3=value3&amp;name4=value4&amp;name5=value5</code></p>
<h4 id="http专有cookie"><a href="#http专有cookie" class="headerlink" title="http专有cookie"></a>http专有cookie</h4><p>服务端可以设置 <code>httpOnly:true</code>，带有该属性的 cookie 客户端无法获取。</p>
<h4 id="缺陷"><a href="#缺陷" class="headerlink" title="缺陷"></a>缺陷</h4><p>可以的情况下所有的 cookie 都会由浏览器作为请求头发送，在 cookie 中存储大量信息会影响到特定域的请求性能，cookie 信息越大完成对服务器请求的时间越长。cookie 的性质和其局限使其并不能作为存储大量信息的理想手段。</p>
<h3 id="storage类型"><a href="#storage类型" class="headerlink" title="storage类型"></a>storage类型</h3><ul>
<li>clear()：删除所有值</li>
<li>getItem(name)：根据指定的名字 name 获取对应的值</li>
<li>key(index)：获得 index 位置处的值的名字</li>
<li>removeItem(name)：删除由 name 指定的名值对</li>
<li>setItem(name,value)：为指定的 name 设置一个对应的值</li>
<li>length：存储在 storage 对象的名值对的数目</li>
</ul>
<p>sessionStorage对象：存储特定于某个会话的数据（该数据只保存到浏览器关闭），可以跨越页面刷新而存在</p>
<p>globalStorage对象：跨越会话存储数据，使用 globalStrorage 是需要指定哪些域可以访问该数据，通过方括号标记使用属性来实现。访问和设置的是特定域名的存储空间（globalStorage对象不是Storage对象，<code>globalStorage[&quot;xxx.xxx.xxx&quot;]</code>才是），而且只能由来自该域名的页面访问（其他子域名都不行），并且对 globalStorage 空间的访问依据发起请求页面的域名、协议和端口来限制的（类似于同源策略）。如果不使用 removeItem 或者 delete 删除或用户为清除浏览器缓存，存储在 globalStorage 属性中的数据会一直保存在磁盘上。</p>
<p>localStorage对象：不能给 localStorage 指定任何访问规则，访问同一个 localStorage 页面必须来自同一个域名（子域名无效）、同一种协议、同一个端口。相当于 <code>globalStorage[location.host]</code>。数据会一直保留直到通过 JavaScript 删除或者是用户清除浏览器缓存。</p>
<p>对 Storage 对象进行任何修改都会在文档上触发 storage 事件。这个事件的 event 对象有一下几种属性：</p>
<ul>
<li>domain：发生变化的存储空间的域名</li>
<li>key：设置或删除的键名</li>
<li>newValue：如果是设置值则是新值，如果是删除键则为 null</li>
<li>oldValue：键被更改之前的值</li>
</ul>
<h3 id="IndexedDB"><a href="#IndexedDB" class="headerlink" title="IndexedDB"></a>IndexedDB</h3><p>浏览器中保存结构化数据的一种数据库，操作完全是异步进行，大多数操作会以请求的方式进行，使用对象保存数据。</p>
<p>IndexedDB数据库只能有同源（相同协议、端口、域名）页面操作，不能跨域共享信息，每个来源的数据库占用的磁盘空间也有限制。</p>
<h3 id="service-worker"><a href="#service-worker" class="headerlink" title="service worker"></a>service worker</h3><p>Service Workers 本质上充当 web应用程序与浏览器之间的代理服务器，也可以在网络可用时作为浏览器和网络间的代理，它们旨在（除其他之外）使得能够创建有效的离线体验，拦截网络请求并基于网络是否可用以及更新的资源是否驻留在服务器上来采取使用的动作，他们还允许访问通知和后台同步API。</p>
<p>目前通常用 service worker 来做缓存文件，提高首屏速度。</p>
<pre><code>// index.js
if (navigator.serviceWorker) {
  navigator.serviceWorker
    .register(&#39;sw.js&#39;)
    .then(function(registration) {
      console.log(&#39;service worker 注册成功&#39;)
    })
    .catch(function(err) {
      console.log(&#39;servcie worker 注册失败&#39;)
    })
}
// sw.js
// 监听 `install` 事件，回调中缓存所需文件
self.addEventListener(&#39;install&#39;, e =&gt; {
  e.waitUntil(
    caches.open(&#39;my-cache&#39;).then(function(cache) {
      return cache.addAll([&#39;./index.html&#39;, &#39;./index.js&#39;])
    })
  )
})

// 拦截所有请求事件
// 如果缓存中已经有请求的数据就直接用缓存，否则去请求数据
self.addEventListener(&#39;fetch&#39;, e =&gt; {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      if (response) {
        return response
      }
      console.log(&#39;fetch source&#39;)
    })
  )
})
</code></pre><blockquote>
<p>参考：<a href="https://yuchengkai.cn/docs/frontend/browser.html#service-worker" target="_blank" rel="noopener">前端进阶之道</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/11/09/browser-process-render/" rel="next" title="browser-process">
                <i class="fa fa-chevron-left"></i> browser-process
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/11/10/browser-cookie-storage/" rel="prev" title="js中的 storage 和 worker">
                js中的 storage 和 worker <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#cookie"><span class="nav-number">1.</span> <span class="nav-text">cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#限制："><span class="nav-number">1.1.</span> <span class="nav-text">限制：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#构成："><span class="nav-number">1.2.</span> <span class="nav-text">构成：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#javascript操作cookie"><span class="nav-number">1.3.</span> <span class="nav-text">javascript操作cookie</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#子cookie"><span class="nav-number">1.4.</span> <span class="nav-text">子cookie</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#http专有cookie"><span class="nav-number">1.5.</span> <span class="nav-text">http专有cookie</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺陷"><span class="nav-number">1.6.</span> <span class="nav-text">缺陷</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#storage类型"><span class="nav-number">2.</span> <span class="nav-text">storage类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IndexedDB"><span class="nav-number">3.</span> <span class="nav-text">IndexedDB</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#service-worker"><span class="nav-number">4.</span> <span class="nav-text">service worker</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
